<template>
  <div class="register">
    <div class="RegisterForm">
      <el-form :model="form" label-width="auto">
        <div style="text-align: center; margin: 0 20px">
          <div>
            <div style="font-size: 25px; font-weight: bold">心有灵“析” - 注册</div>
          </div>
          <div style="margin-top: 50px">
            <el-form :model="form" :rules="rules" @validate="onValidate" ref="formRef">
              <el-form-item prop="username">
                <el-input v-model="form.username" :maxlength="8" type="text" placeholder="用户名">
                  <template #prefix>
                    <el-icon><User /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="password">
                <el-input v-model="form.password" :maxlength="16" type="password" placeholder="密码">
                  <template #prefix>
                    <el-icon><Lock /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="password_repeat">
                <el-input v-model="form.password_repeat" :maxlength="16" type="password" placeholder="确认密码">
                  <template #prefix>
                    <el-icon><Lock /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="email">
                <el-input v-model="form.email" type="email" placeholder="电子邮箱">
                  <template #prefix>
                    <el-icon><Message /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="emailCode">
                <el-input v-model="form.emailCode" type="text" placeholder="邮箱验证码">
                  <template #prefix>
                    <el-icon><Key /></el-icon>
                  </template>
                  <template #append>
                    <el-button @click="sendEmailCode" :disabled="!isEmailValid || countdown < 60">
                      {{ emailCodeButtonText }}
                    </el-button>
                  </template>
                </el-input>
              </el-form-item>
            </el-form>
          </div>
          <div style="margin-top: 80px">
            <el-button style="width: 270px" type="warning" @click="register" plain>立即注册</el-button>
            <el-button style="width: 270px" type="warning" @click="router.push('/')" plain>返回主页</el-button>
          </div>
          <div style="margin-top: 20px">
            <span style="font-size: 14px; line-height: 15px; color: grey">已有账号?</span>
            <el-link type="primary" style="translate: 0 -2px" @click="router.push('/login')">立即登录</el-link>
          </div>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { Lock, User, Message, Key } from "@element-plus/icons-vue";
import router from "@/router";
import { reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import { captchaEmail as captchaEmailApi, register as registerApi } from "@/api/register/index.js";
import to from "await-to-js"; // 确保导入了正确的接口函数

const form = reactive({
  username: "",
  password: "",
  password_repeat: "",
  email: "",
  emailCode: "",
});

const emailCodeButtonText = ref("发送验证码");
const isEmailValid = ref(false);
const timer = ref(null);
const countdown = ref(60); // 验证码倒计时

const validateEmail = (rule, value, callback) => {
  const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  isEmailValid.value = emailRegex.test(value);
  if (!value) {
    return callback(new Error("请输入电子邮箱"));
  } else if (!emailRegex.test(value)) {
    return callback(new Error("请输入有效的电子邮箱地址"));
  } else {
    callback();
  }
};

const validateUsername = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请输入用户名"));
  } else if (!/^[a-zA-Z0-9\u4e00-\u9fa5]+$/.test(value)) {
    callback(new Error("用户名不能包含特殊字符，只能是中文/英文"));
  } else {
    callback();
  }
};

const validatePassword = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请输入密码"));
  } else if (value !== form.password) {
    callback(new Error("两次输入的密码不一致"));
  } else {
    callback();
  }
};

const rules = {
  username: [
    { validator: validateUsername, trigger: ["blur", "change"] },
    { min: 2, max: 8, message: "用户名的长度必须在2-8个字符之间", trigger: ["blur", "change"] },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 16, message: "密码的长度必须在6-16个字符之间", trigger: ["blur", "change"] },
  ],
  password_repeat: [{ validator: validatePassword, trigger: ["blur", "change"] }],
  email: [{ validator: validateEmail, trigger: ["blur", "change"] }],
  emailCode: [{ required: true, message: "请输入邮箱验证码", trigger: "blur" }],
};

const formRef = ref();
const onValidate = (prop, isValid) => {
  if (prop === "email") isEmailValid.value = isValid;
};

const sendEmailCode = async () => {
  if (!isEmailValid.value) return;
  console.log(form);
  const email = form.email;
  console.log("传入前的" + email);

  // 发送验证码邮件
  const [err, res] = await to(captchaEmailApi({ email, businessType: "register" }));
  if (!err) {
    ElMessage.success("验证码已发送至您的邮箱");
    // 启动倒计时
    if (timer.value) clearInterval(timer.value);
    timer.value = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) {
        clearInterval(timer.value);
        emailCodeButtonText.value = "重新发送";
        countdown.value = 60;
      } else {
        emailCodeButtonText.value = `${countdown.value}秒后重发`;
      }
    }, 1000);
  } else {
    // // 如果响应状态码不是200，显示错误消息
    // ElMessage.error(`验证码发送失败: ${response.msg}`);
    // 捕获并处理任何网络或API调用错误
    ElMessage.error(`验证码发送失败: ${err.message || "未知错误"}`);
  }
};

const register = async () => {
  // 使用form.value来访问表单数据
  const [err, res] = await to(
    registerApi({
      username: form.username,
      password: form.password,
      email: form.email,
      emailCode: form.emailCode,
    })
  );
  if (!err) {
    // 提示用户注册成功
    ElMessage.success("注册成功，欢迎加入我们");
    // 可能还需要跳转到登录页面或其他页面
    router.push("/login");
  } else {
    // 处理网络或其他非业务逻辑错误
    ElMessage.error(`注册请求失败: ${err.message || "未知错误"}`);
  }
};
</script>

<style scoped>
.RegisterForm {
  width: 600px;
  height: 600px; /* Increased height to accommodate new fields */
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
  border-radius: 10px;
  justify-content: center;
  align-items: center;
  margin: auto;
}

.register {
  height: 100vh;
  background: linear-gradient(to bottom, #a6caeb, #bee6cb);
  display: flex;
}

.title {
  font-size: 36px;
  margin-top: 30px;
  margin-bottom: 50px;
}
</style>
